<?php defined('SYSPATH') or die('No direct script access.');

class Model_Review_Recensee extends Model_Review_Abstract
{ 
    protected $_table_name = 'recensee_reviews';  
    
    public static $_availableExperiences = array(
        1 => 'менее месяца',
        2 => 'несколько месяцев',
        3 => 'более года',
    );
    
    public function get_entity()
    {
        return 'recensee';
    }
    
    public function get_reviews_query($entity)
    {
        // Если ищем по товару или модели
        if ($entity instanceof Model_Product) {
            $model_id = $entity->model_id; 
        } else if ($entity instanceof Model_Model) {
            $model_id = $entity->id;
        } else {
            throw new Model_Exception('Некорректный тип');
        }
        return DB::select(
                array(DB::expr('\'recensee\''), 'entity'),
                'id',
                'model_id',
                array(DB::expr('NULL'), 'source_id'),
                array(DB::expr('(SELECT IF(nick = \'\', email, nick) FROM users WHERE id = table.user_id)'), 'user_nick'),
                array(DB::expr('NULL'), 'user_link'),
                'rating',
                'experience',
                'pluses',
                'minuses',
                'text',
                array(DB::expr('NULL'), 'link'), 
                'date',
                'usefulness',
                'u_yes',
                'u_no'
            )
            ->from(array($this->_table_name, 'table'))
            ->where('model_id', '=', $model_id);
    }
    
    public function add_review(Model_Model $model, Model_User $user, $text, $pluses, $minuses, $rating, $experience)
    {
        $this->model_id = $model->id;
        $this->user_id  = $user->id;
        $this->text     = strip_tags($text);
        $this->pluses   = strip_tags($pluses);
        $this->minuses  = strip_tags($minuses);
        $this->rating   = $rating;
        if ($experience) {
            $experience = self::$_availableExperiences[$experience];
            $this->experience = $experience;
        }
        $this->date     = time();
        $this->save();
        
        $model->change_count_reviews();
        if ($rating) {
            $model->change_count_stars($rating);
        }
        
        Model_Review::clear_cache($model);
        return $this;  
    }    
}